package com.example.petshopping.ui.address.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petshopping.R;
import com.example.petshopping.ui.address.adapter.RegionAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class RegionPickerDialog extends Dialog {

    private Context context;
    private RecyclerView recyclerProvinces;
    private RecyclerView recyclerCities;
    private RecyclerView recyclerDistricts;
    private TextView tabProvince;
    private TextView tabCity;
    private TextView tabDistrict;
    private TextView btnCancel;
    private TextView btnConfirm;

    private RegionAdapter provinceAdapter;
    private RegionAdapter cityAdapter;
    private RegionAdapter districtAdapter;

    private Map<String, Map<String, List<String>>> regionData;
    private String selectedProvince = "";
    private String selectedCity = "";
    private String selectedDistrict = "";

    private OnRegionPickListener listener;

    public RegionPickerDialog(@NonNull Context context) {
        super(context, R.style.DialogTheme);
        this.context = context;
        initRegionData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_region_picker);

        // 设置底部对话框样式
        Window window = getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(lp);
        }

        initViews();
        setupAdapters();
        setupListeners();
        loadProvinceData();
    }

    private void initViews() {
        recyclerProvinces = findViewById(R.id.recycler_provinces);
        recyclerCities = findViewById(R.id.recycler_cities);
        recyclerDistricts = findViewById(R.id.recycler_districts);
        tabProvince = findViewById(R.id.tab_province);
        tabCity = findViewById(R.id.tab_city);
        tabDistrict = findViewById(R.id.tab_district);
        btnCancel = findViewById(R.id.btn_cancel);
        btnConfirm = findViewById(R.id.btn_confirm);
    }

    private void setupAdapters() {
        // 省份
        provinceAdapter = new RegionAdapter(context);
        recyclerProvinces.setLayoutManager(new LinearLayoutManager(context));
        recyclerProvinces.setAdapter(provinceAdapter);

        // 城市
        cityAdapter = new RegionAdapter(context);
        recyclerCities.setLayoutManager(new LinearLayoutManager(context));
        recyclerCities.setAdapter(cityAdapter);

        // 区县
        districtAdapter = new RegionAdapter(context);
        recyclerDistricts.setLayoutManager(new LinearLayoutManager(context));
        recyclerDistricts.setAdapter(districtAdapter);

        // 省份选择监听
        provinceAdapter.setOnRegionSelectedListener((province, position) -> {
            selectedProvince = province;
            selectedCity = "";
            selectedDistrict = "";
            
            tabProvince.setText(province);
            tabCity.setText("城市");
            tabDistrict.setText("区县");
            
            tabCity.setVisibility(View.VISIBLE);
            tabDistrict.setVisibility(View.GONE);
            
            switchTab(1); // 切换到城市选项卡
            loadCityData();
        });

        // 城市选择监听
        cityAdapter.setOnRegionSelectedListener((city, position) -> {
            selectedCity = city;
            selectedDistrict = "";
            
            tabCity.setText(city);
            tabDistrict.setText("区县");
            
            tabDistrict.setVisibility(View.VISIBLE);
            
            switchTab(2); // 切换到区县选项卡
            loadDistrictData();
        });

        // 区县选择监听
        districtAdapter.setOnRegionSelectedListener((district, position) -> {
            selectedDistrict = district;
            tabDistrict.setText(district);
        });
    }

    private void setupListeners() {
        // 取消按钮
        btnCancel.setOnClickListener(v -> dismiss());

        // 确认按钮
        btnConfirm.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRegionPicked(selectedProvince, selectedCity, selectedDistrict);
            }
            dismiss();
        });

        // 标签切换
        tabProvince.setOnClickListener(v -> switchTab(0));
        tabCity.setOnClickListener(v -> {
            if (!selectedProvince.isEmpty()) {
                switchTab(1);
            }
        });
        tabDistrict.setOnClickListener(v -> {
            if (!selectedCity.isEmpty()) {
                switchTab(2);
            }
        });
    }

    private void switchTab(int tabIndex) {
        // 重置所有标签样式
        tabProvince.setTextColor(context.getResources().getColor(android.R.color.darker_gray));
        tabCity.setTextColor(context.getResources().getColor(android.R.color.darker_gray));
        tabDistrict.setTextColor(context.getResources().getColor(android.R.color.darker_gray));

        // 隐藏所有RecyclerView
        recyclerProvinces.setVisibility(View.GONE);
        recyclerCities.setVisibility(View.GONE);
        recyclerDistricts.setVisibility(View.GONE);

        // 设置选中的标签样式并显示对应的RecyclerView
        switch (tabIndex) {
            case 0: // 省份
                tabProvince.setTextColor(context.getResources().getColor(android.R.color.holo_purple));
                recyclerProvinces.setVisibility(View.VISIBLE);
                break;
            case 1: // 城市
                tabCity.setTextColor(context.getResources().getColor(android.R.color.holo_purple));
                recyclerCities.setVisibility(View.VISIBLE);
                break;
            case 2: // 区县
                tabDistrict.setTextColor(context.getResources().getColor(android.R.color.holo_purple));
                recyclerDistricts.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void loadProvinceData() {
        List<String> provinces = new ArrayList<>(regionData.keySet());
        provinceAdapter.updateData(provinces);
    }

    private void loadCityData() {
        if (regionData.containsKey(selectedProvince)) {
            Map<String, List<String>> cities = regionData.get(selectedProvince);
            cityAdapter.updateData(new ArrayList<>(cities.keySet()));
        }
    }

    private void loadDistrictData() {
        if (regionData.containsKey(selectedProvince)) {
            Map<String, List<String>> cities = regionData.get(selectedProvince);
            if (cities.containsKey(selectedCity)) {
                List<String> districts = cities.get(selectedCity);
                districtAdapter.updateData(districts);
            }
        }
    }

    public void setSelectedRegion(String province, String city, String district) {
        if (province != null && !province.isEmpty()) {
            this.selectedProvince = province;
            tabProvince.setText(province);
            tabCity.setVisibility(View.VISIBLE);
            
            if (city != null && !city.isEmpty()) {
                this.selectedCity = city;
                tabCity.setText(city);
                tabDistrict.setVisibility(View.VISIBLE);
                
                if (district != null && !district.isEmpty()) {
                    this.selectedDistrict = district;
                    tabDistrict.setText(district);
                }
            }
        }
    }

    public void setOnRegionPickListener(OnRegionPickListener listener) {
        this.listener = listener;
    }

    private void initRegionData() {
        regionData = new HashMap<>();
        
        // 北京市
        Map<String, List<String>> beijing = new HashMap<>();
        beijing.put("北京市", Arrays.asList("东城区", "西城区", "朝阳区", "海淀区", "丰台区", "石景山区",
                "门头沟区", "房山区", "通州区", "顺义区", "昌平区", "大兴区", "怀柔区", "平谷区", "密云区", "延庆区"));
        regionData.put("北京市", beijing);
        
        // 上海市
        Map<String, List<String>> shanghai = new HashMap<>();
        shanghai.put("上海市", Arrays.asList("黄浦区", "徐汇区", "长宁区", "静安区", "普陀区", "虹口区", 
                "杨浦区", "浦东新区", "闵行区", "宝山区", "嘉定区", "金山区", "松江区", "青浦区", "奉贤区", "崇明区"));
        regionData.put("上海市", shanghai);
        
        // 广东省
        Map<String, List<String>> guangdong = new HashMap<>();
        guangdong.put("广州市", Arrays.asList("越秀区", "海珠区", "荔湾区", "天河区", "白云区", "黄埔区",
                "番禺区", "花都区", "南沙区", "从化区", "增城区"));
        guangdong.put("深圳市", Arrays.asList("福田区", "罗湖区", "南山区", "宝安区", "龙岗区", "盐田区",
                "龙华区", "坪山区", "光明区"));
        regionData.put("广东省", guangdong);
        
        // 山东省
        Map<String, List<String>> shandong = new HashMap<>();
        shandong.put("济南市", Arrays.asList("历下区", "市中区", "槐荫区", "天桥区", "历城区", "长清区",
                "章丘区", "济阳区", "莱芜区", "钢城区", "平阴县", "商河县"));
        shandong.put("青岛市", Arrays.asList("市南区", "市北区", "李沧区", "城阳区", "崂山区", "黄岛区",
                "即墨区", "胶州市", "平度市", "莱西市"));
        regionData.put("山东省", shandong);
    }

    public interface OnRegionPickListener {
        void onRegionPicked(String province, String city, String district);
    }
} 